package com.xingfly.product.category;

import com.xingfly.product.sdk.command.CreateCategoryCommand;
import com.xingfly.product.sdk.representaion.CategoryRepresentation;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by SuperS on 2019/11/21.
 *
 * @author SuperS
 */
@Service
public class CategoryAppService {

    private CategoryRepository categoryRepository;

    public CategoryAppService(CategoryRepository categoryRepository) {
        this.categoryRepository = categoryRepository;
    }

    @Transactional(rollbackFor = Exception.class)
    public CategoryId createCategory(CreateCategoryCommand command) {
        Category category = Category.create(command.getName(), command.getDescription());
        Category p = this.categoryRepository.save(category);
        return p.getId();
    }

    public CategoryRepresentation findById(String id) {
        Category category = this.categoryRepository.findById(CategoryId.from(id))
                .orElseThrow(() -> new RuntimeException("Category Not Found!"));
        return category.toRepresentation();
    }

}
